package com.hll.spring_book.aop;

import org.springframework.stereotype.Component;
import org.springframework.web.cors.CorsConfiguration;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author: Mr.Hu
 * @create: 2021-04-23 21:30
 */
@Component
public class CorsFilter implements Filter {
  /*cors跨域设置*/
  @Override
  public void doFilter(
      ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
      throws IOException, ServletException {
    HttpServletRequest request = (HttpServletRequest) servletRequest;
    HttpServletResponse response = (HttpServletResponse) servletResponse;

    response.setHeader("Access-Control-Allow-Credentials", "true");
    response.setHeader("Access-Control-Allow-Headers", CorsConfiguration.ALL);
    response.setHeader("Access-Control-Allow-Methods", CorsConfiguration.ALL);
    response.setHeader("Access-Control-Max-Age", "3600");
    /*其实写一个allow列表,只允许列表中的进入*/
    /*在vue项目没打包时运行，下面的header值为"*", 但vue打包后用express运行时报错，搜了很久才解决,值就是ip:port */
    response.setHeader("Access-Control-Allow-Origin", request.getHeader("origin"));
    // 执行
    filterChain.doFilter(servletRequest, servletResponse);
  }
}
